{"componentChunkName":"component---src-templates-post-jsx","path":"/[BOJ]14502/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","excerpt":"문제 인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다.\n연구소는 크기가 N×M인 직사각형으로 나타낼 수 있으며, 직사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한…","html":"<h2>문제</h2>\n<p>인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다.\n연구소는 크기가 N×M인 직사각형으로 나타낼 수 있으며, 직사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다.\n일부 칸은 바이러스가 존재하며, 이 바이러스는 상하좌우로 인접한 빈 칸으로 모두 퍼져나갈 수 있다. 새로 세울 수 있는 벽의 개수는 3개이며, 꼭 3개를 세워야 한다.\n예를 들어, 아래와 같이 연구소가 생긴 경우를 살펴보자.</p>\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">2 0 0 0 1 1 0\n0 0 1 0 1 2 0\n0 1 1 0 1 0 0\n0 1 0 0 0 0 0\n0 0 0 0 0 1 1\n0 1 0 0 0 0 0\n0 1 0 0 0 0 0</code>\n        </deckgo-highlight-code>\n<p>이때, 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 곳이다. 아무런 벽을 세우지 않는다면, 바이러스는 모든 빈 칸으로 퍼져나갈 수 있다. 2행 1열, 1행 2열, 4행 6열에 벽을 세운다면 지도의 모양은 아래와 같아지게 된다.</p>\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">2 1 0 0 1 1 0\n1 0 1 0 1 2 0\n0 1 1 0 1 0 0\n0 1 0 0 0 1 0\n0 0 0 0 0 1 1\n0 1 0 0 0 0 0\n0 1 0 0 0 0 0</code>\n        </deckgo-highlight-code>\n<p>바이러스가 퍼진 뒤의 모습은 아래와 같아진다.</p>\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">2 1 0 0 1 1 2\n1 0 1 0 1 2 2\n0 1 1 0 1 2 2\n0 1 0 0 0 1 2\n0 0 0 0 0 1 1\n0 1 0 0 0 0 0\n0 1 0 0 0 0 0</code>\n        </deckgo-highlight-code>\n<p>벽을 3개 세운 뒤, 바이러스가 퍼질 수 없는 곳을 안전 영역이라고 한다. 위의 지도에서 안전 영역의 크기는 27이다. 연구소의 지도가 주어졌을 때 얻을 수 있는 안전 영역 크기의 최댓값을 구하는 프로그램을 작성하시오.</p>\n<h2>입, 출력</h2>\n<p>입력</p>\n<ul>\n<li>첫째 줄에 지도의 세로 크기 N과 가로 크기 M이 주어진다. (3 ≤ N, M ≤ 8)</li>\n<li>둘째 줄부터 N개의 줄에 지도의 모양이 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 위치이다. 2의 개수는 2보다 크거나 같고, 10보다 작거나 같은 자연수이다.</li>\n<li>빈 칸의 개수는 3개 이상이다.</li>\n</ul>\n<p>출력</p>\n<ul>\n<li>첫째 줄에 얻을 수 있는 안전 영역의 최대 크기를 출력한다.</li>\n</ul>\n<h3>📍 <strong>Logic</strong></h3>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Lab {\n    Queue&lt;Loc&gt; locQueue;\n    int N, M;\n    int safeArea = 0;\n    int[][] map;\n    int[][] copyMap;\n    int[] rangeX = { -1, 0, 1, 0 };\n    int[] rangeY = { 0, 1, 0, -1 };\n\n    Loc[] orgSafe;\n    int idx0 = 0;\n    ...\n        \n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>연구소의 정보를 관리하는 클래스</li>\n<li>원본 연구소 정보를 저장하는 <code class=\"language-text\">map</code> 과 바이러스를 실제로 퍼뜨릴 <code class=\"language-text\">copyMap</code> 을 사용한다.</li>\n<li>또한 벽을 세울 공간들을 저장하는 <code class=\"language-text\">orgSafe</code> 배열을 사용한다.</li>\n<li><code class=\"language-text\">setWall()</code> 재귀 호출로 벽을 세우고, 벽을 다 세운 다음, <code class=\"language-text\">spreadVirus()</code> 에서 BFS 방식으로 바이러스를 퍼뜨린다.</li>\n<li>이후, <code class=\"language-text\">countAndReset()</code> 으로 바이러스가 퍼진 이후의 안전 영역을 카운트하고, <code class=\"language-text\">map</code> 을 이용해 <code class=\"language-text\">copyMap</code> 을 바이러스가 퍼지기 전 상태로 돌려놓는다.</li>\n</ul>\n<h3>📄 <strong>CODE</strong></h3>\n<details>\n  <summary>코드 보기/접기💫</summary>\n    <div markdown=\"1\">\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\nclass Loc {\n    int x, y;\n\n    public Loc(int x, int y) {\n        this.x = x;\n        this.y = y;\n    }\n}\n\nclass Lab {\n    Queue&lt;Loc&gt; locQueue;\n    int N, M;\n    int safeArea = 0;\n    int[][] map;\n    int[][] copyMap;\n    int[] rangeX = { -1, 0, 1, 0 };\n    int[] rangeY = { 0, 1, 0, -1 };\n\n    Loc[] orgSafe;\n    int idx0 = 0;\n\n    public Lab (int N, int M) {\n        this.N = N;\n        this.M = M;\n        map = new int[N][M];\n        copyMap = new int[N][M];\n        orgSafe = new Loc[N*M];\n        locQueue = new LinkedList&lt;&gt;();\n    }\n\n    public int findMaxSafeArea() {\n        setWall(0,3);\n        return safeArea;\n    }\n\n    private void setWall(int idx, int count) {\n        if (count == 0) {\n            spreadVirus();\n            int result = countAndReset();\n            if (safeArea &lt; result) safeArea = result;\n        } else {\n            count--;\n            for (int i = idx; i &lt; idx0; i++) {\n                copyMap[orgSafe[i].x][orgSafe[i].y] = 1;\n                setWall(i + 1, count);\n                copyMap[orgSafe[i].x][orgSafe[i].y] = 0;\n            }\n        }\n    }\n\n    private void spreadVirus() {\n        for (int i = 0; i &lt; locQueue.size(); i++) {\n            Loc tmpLoc = locQueue.poll();\n            bfs(tmpLoc.x, tmpLoc.y);\n            locQueue.add(tmpLoc);\n        }\n    }\n\n    private void bfs(int x, int y) {\n        Queue&lt;Loc&gt; queue = new LinkedList&lt;&gt;();\n        queue.add(new Loc(x, y));\n\n        while (!queue.isEmpty()){\n            Loc tmp = queue.poll();\n            for (int i = 0; i &lt; 4; i++) {\n                int nx = tmp.x + rangeX[i], ny = tmp.y + rangeY[i];\n                if (nx &lt; 0 || nx &gt;= N || ny &lt; 0 || ny &gt;= M) continue;\n                if (copyMap[nx][ny] == 0) {\n                    queue.add(new Loc(nx, ny));\n                    copyMap[nx][ny] = 2;\n                }\n            }\n        }\n    }\n\n    private int countAndReset() {\n        int count = 0;\n        for (int i = 0; i &lt; N; i++) {\n            for (int j = 0; j &lt; M; j++) {\n                if (copyMap[i][j] == 0) count++;\n                if (copyMap[i][j] == 2) {\n                    if (locQueue.contains(new Loc(i, j))) continue;\n                    copyMap[i][j] = map[i][j];\n                }\n            }\n        }\n        return count;\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) throws IOException {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n        String[] line = br.readLine().split(&quot; &quot;);\n        int N = Integer.parseInt(line[0]);\n        int M = Integer.parseInt(line[1]);\n\n        Lab lab = new Lab(N, M);\n\n        for (int i = 0; i &lt; N; i++) {\n            lab.map[i] = Arrays.stream(br.readLine().split(&quot; &quot;)).mapToInt(Integer::parseInt).toArray();\n            for (int j = 0; j &lt; M; j++) {\n                if (lab.map[i][j] == 2)\n                    lab.locQueue.add(new Loc(i, j));\n                else if (lab.map[i][j] == 0)\n                    lab.orgSafe[lab.idx0++] = new Loc(i, j);\n                lab.copyMap[i][j] = lab.map[i][j];\n            }\n        }\n\n        br.close();\n\n        System.out.println(lab.findMaxSafeArea());\n    }\n}</code>\n        </deckgo-highlight-code>\n  \t</div>\n</details>\n<h3>✏️ <strong>Review</strong></h3>\n<ul>\n<li>원래의 연구소 정보를 간직하기 위해 <code class=\"language-text\">map</code> 과 <code class=\"language-text\">copyMap</code> 배열을 두고 진행했는데, 계속 두 배열이 동기화된 것마냥 값이 같이 변경되고 있었다. 아무래도 <code class=\"language-text\">lab.map[i] = lab.copyMap[i];</code> 이 코드 때문에 인스턴스의 주소 공유나 참조의 문제일거라 생각해 검색해보니 아니나 다를까 \"얕은 복사와 깊은 복사\" 문제였다. 한 번 정리해야겠다.</li>\n<li>바이러스가 퍼진 이후 다시 원상복구할때, 세운 벽까지 없애버리는 초기화 과정떄문에 값이 계속 잘못 나왔다. 초기화 과정은 항상 잘 확인하자.</li>\n</ul>\n<h3>📕 출처</h3>\n<p>Baekjoon : <a href=\"https://www.acmicpc.net/problem/14502\">https://www.acmicpc.net/problem/14502</a></p>","frontmatter":{"title":"👩‍💻 14502. 연구소","date":"March 19, 2022","update":"March 19, 2022","tags":["그래프이론","그래프탐색","BFS","브루트포스"],"series":"👩‍💻 BOJ"},"fields":{"slug":"/[BOJ]14502/","readingTime":{"minutes":7.535}}},"seriesList":{"edges":[{"node":{"id":"27733333-3aad-5771-a1a1-27b4de4b4a01","fields":{"slug":"/[BOJ]2225/"},"frontmatter":{"title":"👩‍💻 2225. 합분해"}}},{"node":{"id":"548ba188-2afe-5575-b79f-107c6c65b07d","fields":{"slug":"/[BOJ]1012/"},"frontmatter":{"title":"👩‍💻 1012. 유기농 배추"}}},{"node":{"id":"0c712680-130f-5fa5-8c3b-3632dd5d1af0","fields":{"slug":"/[BOJ]1260/"},"frontmatter":{"title":"👩‍💻 1260. DFS와 BFS"}}},{"node":{"id":"0e07a592-06ce-5e01-b5e1-95398330372e","fields":{"slug":"/[BOJ]1707/"},"frontmatter":{"title":"👩‍💻 1707. 이분그래프"}}},{"node":{"id":"df12bfec-ed5c-5fc4-8442-0a4b3f9759a3","fields":{"slug":"/[BOJ]2668/"},"frontmatter":{"title":"👩‍💻 2668. 숫자 고르기"}}},{"node":{"id":"01bbb6dc-812c-5223-87c5-53bf04c0d0a6","fields":{"slug":"/[BOJ]9466/"},"frontmatter":{"title":"👩‍💻 9466. 텀 프로젝트"}}},{"node":{"id":"abc306b3-c3a6-552a-8979-e82d506b3921","fields":{"slug":"/[BOJ]2146/"},"frontmatter":{"title":"👩‍💻 2146. 다리 만들기"}}},{"node":{"id":"b3394e53-5e9a-595e-8da4-bb3debd220c0","fields":{"slug":"/[BOJ]5014/"},"frontmatter":{"title":"👩‍💻 5014. 스타트 링크"}}},{"node":{"id":"be297703-e778-5727-8019-6954bc95da3a","fields":{"slug":"/[BOJ]11559/"},"frontmatter":{"title":"👩‍💻 11559. Puyo Puyo"}}},{"node":{"id":"ddf11545-d468-5269-94b1-5daa2720e886","fields":{"slug":"/[BOJ]17471/"},"frontmatter":{"title":"👩‍💻 17471. 게리맨더링"}}},{"node":{"id":"8d77114d-fc6e-5de2-a3ca-c3b250425a56","fields":{"slug":"/[BOJ]2437/"},"frontmatter":{"title":"👩‍💻 2437. 저울"}}},{"node":{"id":"9a8942ce-552f-51ae-b304-0d0fab8f2eba","fields":{"slug":"/[BOJ]14891/"},"frontmatter":{"title":"👩‍💻 14891. 톱니바퀴"}}},{"node":{"id":"f1c04e8a-df0a-5294-949f-5f3a483cbcb0","fields":{"slug":"/[BOJ]14503/"},"frontmatter":{"title":"👩‍💻 14503. 로봇 청소기"}}},{"node":{"id":"883b6ecf-7528-5c16-92fa-edf12a64e80e","fields":{"slug":"/[BOJ]3190/"},"frontmatter":{"title":"👩‍💻 3190. 뱀"}}},{"node":{"id":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","fields":{"slug":"/[BOJ]14502/"},"frontmatter":{"title":"👩‍💻 14502. 연구소"}}},{"node":{"id":"50eef059-4e55-5f14-a9cf-fb01b6506f02","fields":{"slug":"/[BOJ]17779/"},"frontmatter":{"title":"👩‍💻 17779. 게리맨더링 2"}}},{"node":{"id":"aa67d90b-4801-574c-b225-56c23737a5e2","fields":{"slug":"/[BOJ]2579/"},"frontmatter":{"title":"👩‍💻 2579. 계단 오르기"}}},{"node":{"id":"9db6b43b-963a-5ebd-b72b-69936cf37858","fields":{"slug":"/[BOJ]14499/"},"frontmatter":{"title":"👩‍💻 14499. 주사위 굴리기"}}},{"node":{"id":"6a79cddd-dc1b-5e34-8a84-af313c37de0e","fields":{"slug":"/[BOJ]15685/"},"frontmatter":{"title":"👩‍💻 15685. 드래곤 커브"}}},{"node":{"id":"5e001d34-d985-545b-83ec-7f1c7caea286","fields":{"slug":"/[BOJ]17144/"},"frontmatter":{"title":"👩‍💻 17144. 미세먼지 안녕!"}}},{"node":{"id":"1d132410-9377-5e55-85b9-4664ff64de73","fields":{"slug":"/[BOJ]9935/"},"frontmatter":{"title":"👩‍💻 9935. 문자열 폭발"}}},{"node":{"id":"e13ff8d6-9b02-56c0-83e2-1d3144f70e1d","fields":{"slug":"/[BOJ]16472/"},"frontmatter":{"title":"👩‍💻 16472. 고냥이"}}},{"node":{"id":"0f782160-aaa9-5c54-80c0-72a15172dd16","fields":{"slug":"/[BOJ]1083/"},"frontmatter":{"title":"👩‍💻 1083. 소트"}}},{"node":{"id":"fef58615-9e18-5f50-8d09-3d1e2839342f","fields":{"slug":"/[BOJ]20922/"},"frontmatter":{"title":"👩‍💻 20922. 겹치는 건 싫어"}}},{"node":{"id":"7ca89240-c65f-5cb4-aeef-c5f1605ebd00","fields":{"slug":"/[BOJ]16172/"},"frontmatter":{"title":"👩‍💻 16172. 나는 친구가 적다(Large)"}}}]},"previous":{"fields":{"slug":"/[BOJ]3190/"},"frontmatter":{"title":"👩‍💻 3190. 뱀"}},"next":{"fields":{"slug":"/[Java지식]얕은복사&깊은복사/"},"frontmatter":{"title":"📃 얕은 복사와 깊은 복사"}}},"pageContext":{"id":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","series":"👩‍💻 BOJ","previousPostId":"883b6ecf-7528-5c16-92fa-edf12a64e80e","nextPostId":"92c9220c-c4b0-59a2-a626-5a22f979bf39"}},"staticQueryHashes":[]}